package cn.com.callback;

import cn.com.elite.EliteBean;
import cn.com.kh.KHUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Title: AutoSmsTask*
 * @Description: 根据配置创建短信发送任务-按线程号处理
 * @author: th* @date 2022-6-16 17:00:00
 */

public class apiTaskSms implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiTaskSms.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject resJson = new JSONObject();

        String threadid = request.getParameter("threadid"); //传入线程号
        log.info("接收调用线程号信息：" + threadid);

        long startTime = System.currentTimeMillis();
        long tstartTime = System.currentTimeMillis();

        int succNum = 0;
        int failNum = 0;
        try {
            //非空校验
            String dealMessage = KHUtil.isNullMSG("threadid", threadid);

            if (!KHUtil.isNull(dealMessage)) {
                resJson.put("code", "-1");
                resJson.put("msg", "调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                return resJson.toString();
            }

            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            String selectSQL = '''Select R1.Task_Name,
                                       R1.Table_Name,
                                       R1.Identification,
                                       R1.Identification_Content,
                                       R1.Task_Type,
                                       R1.Trading_Day,
                                       R1.Template_Id,
                                       R1.Template_Values,
                                       R1.Template_Values_Field,
                                       R1.Task_State,
                                       R1.Remark,
                                       R2.Description,
                                       R2.Documentpath
                                  From Pa_Sms_Task_Batch R1
                                  Left Join Doctemplate R2
                                    On R2.Doctemplate_Id = R1.Template_Id
                                 Where R1.Rec_Guid = ? And Task_Type = 'apisms\'''';
            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, threadid);
            log.debug("查询短信配置完成-处理时长(毫秒):" + (System.currentTimeMillis() - startTime));

            // 开始处理
            if (selectExits.size() > 0) {

                Map selectExitsm = selectExits.get(0);
                String Task_Name = selectExitsm.get("Task_Name");
                String Table_Name = selectExitsm.get("Table_Name");
                String Identification = selectExitsm.get("Identification");
                String Identification_Content = selectExitsm.get("Identification_Content");
                String Task_Type = selectExitsm.get("Task_Type");
                String Trading_Day = selectExitsm.get("Trading_Day");
                String Template_Id = selectExitsm.get("Template_Id");
                String Template_Values = selectExitsm.get("Template_Values");
                String Template_Values_Field = selectExitsm.get("Template_Values_Field");
                String Documentpath = selectExitsm.get("Documentpath");
                log.debug("自动发送短信-计划名称: " + Task_Name + " 数据表: " + Table_Name + " 其他参数: " + selectExits.get(0).toString());

                log.debug("Template_Values_Field:"+Template_Values_Field);

                if(!KHUtil.isNull(Template_Values_Field)){
                    Template_Values_Field=","+Template_Values_Field;
                }

                SqlRowSet selectRow = null;
                try {
                    tstartTime = System.currentTimeMillis();
                    String getDataSQL = '''Select R1.Rec_Guid, R1.Mobile''' + Template_Values_Field + '''
                                          From Dws.''' + Table_Name + ''' R1
                                          Left Join Documentout R2
                                            On R1.Rec_Guid = R2.Customer_Guid
                                         Where R2.Documentout_Guid Is Null
                                           And R1.Rec_Guid Is Not Null''';

                    if (!KHUtil.isNull(Identification)) {
                        getDataSQL = getDataSQL + " And R1." + Identification + " = '" + Identification_Content + "'";
                        log.debug("存在任务标识字段:" + getDataSQL);
                    }
                    log.debug("查询平安短信数据SQL:" + getDataSQL);

                    selectRow = jt.queryForRowSet(getDataSQL);
                    log.debug("查询平安短信数据查询完成-处理时长(毫秒):" + (System.currentTimeMillis() - tstartTime));
                } catch (Exception e) {
                    log.error("查询平安短信数据异常!", e);
                    resJson.put("code", "-1");
                    resJson.put("msg", "调用线程号查询配置信息异常:" + e.getMessage() + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                    return resJson.toString();
                }

                String[] fieldMap = Template_Values.split(",");

                int fieldNum = fieldMap.size();
                int loogNum = 0;
                String Rec_Guid = "";
                String Mobile = "";
                String tempDocumentpath = "";
                JSONObject tempDocumentpath2 = new JSONObject();
                String[] fieldArr = null;
                while (selectRow.next()) {
                    loogNum++;
                    try {
                        Rec_Guid = selectRow.getString("Rec_Guid");
                        Mobile = selectRow.getString("Mobile");

                        tempDocumentpath2.clear();
                        tempDocumentpath = Documentpath;
                        for (int i = 0; i < fieldNum; i++) {
                            int reIndex=fieldMap[i].indexOf(":");
                            if(reIndex>-1){
                                fieldArr = fieldMap[i].split(":");
                                String paramField = fieldArr[0];
                                String paramValue = selectRow.getString(fieldArr[1]);
                                // 生成短信发送内容
                                tempDocumentpath = tempDocumentpath.replace("[\$" + paramField + "\$]", paramValue);

                                // 生成短信发送参数
                                tempDocumentpath2.put(paramField, paramValue);
                            }
                        }
                        log.debug("[" + loogNum + "]编号: " + Rec_Guid + " 处理后待发送短信: " + tempDocumentpath + " 处理后待发送报文: " + tempDocumentpath2.toString());

                        if (!KHUtil.isNull(Mobile)) {
                            boolean sendResult = sendDBDeal(jt, Mobile, tempDocumentpath, tempDocumentpath2.toString(), Template_Id, Rec_Guid, threadid + "-" + Task_Name);
                            log.debug("[" + loogNum + "]编号: " + Rec_Guid + "短信发送结果:" + sendResult);
                            if (sendResult) {
                                succNum++;
                            } else {
                                failNum++;
                            }
                        } else {
                            failNum++;
                            log.debug("[" + loogNum + "]编号: " + Rec_Guid + "短信发送失败");
                        }
                    } catch (Exception e) {
                        failNum++;
                        log.error("[" + loogNum + "]编号: " + Rec_Guid + "短信发送异常:", e);
                    }

                }

                String dealResult = "全部短信数据处理完成,总数:" + loogNum + " 成功数量:" + succNum + " 失败数量:" + failNum + "-处理时长(毫秒):" + (System.currentTimeMillis() - startTime);
                resJson.put("code", "1");
                resJson.put("msg", dealResult);
                log.debug(dealResult);

            } else {
                String dealResult = "调用线程号查询配置信息异常:" + selectExits.toString() + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime);
                resJson.put("code", "-1");
                resJson.put("msg", dealResult);
                log.debug(dealResult);
            }

        } catch (Exception e) {
            log.error("处理异常!", e);
            resJson.put("code", "-1");
            resJson.put("msg", "短信发送任务-按线程号处理异常-线程号:" + threadid + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
        }
        return resJson.toString(); ;
    }

    public static boolean sendDBDeal(JdbcTemplate jt, String mobile, String Documentpath, String Documentpath2, String Doctemplate_Id, String Rec_Guid, String threadid) {
        try {
            // 生成短信发送ID
            String MsgID = System.currentTimeMillis() +new Random().nextInt(99999).toString();
            String insertSQL = '''Insert Into Documentout
                                              (Documentout_Guid,
                                               Doctype,
                                               Status,
                                               Trialcount,
                                               Trialcountlimit,
                                               Documentpath,
                                               Documentpath2,
                                               Handleby_Id,
                                               Handlegroup_Id,
                                               Customer_Guid,
                                               Createdby,
                                               Createddate,
                                               Expectedstartdate,
                                               Documentto,
                                               Lasttrydatetime,
                                               Sub_Doctype,
                                               Msgid,
                                               Template_Id,
                                               Send_Type,
                                               Stringfield1)
                                            Values
                                              (UUID(),
                                               3,
                                               0,
                                               0,
                                               3,
                                               ?,
                                               ?,
                                               ?,
                                               ?,
                                               ?,
                                               ?,
                                               Now(),
                                               Now(),
                                               ?,
                                               Null,
                                               '自动任务短信',
                                               ?,
                                               ?,
                                               '3',
                                               ?)''';

            int insertNum = jt.update(insertSQL, Documentpath, Documentpath2, "SELITE", "SYSTEM", Rec_Guid, "SELITE", mobile, MsgID, Doctemplate_Id, threadid);
            if (insertNum > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("发送短信DB处理异常!", e);
            return false;
        }
    }
}